import 'package:flutter/cupertino.dart';
import 'package:flutter_base/bean/home/home_banner_entity.dart';

import '../../bean/home/home_article_list_entity.dart';
import '../../http/api.dart';


///
/// @DIR_PATH：lib/viewmodel/home
/// @TIME：2024/5/4 14:37
/// @AUTHOR：starr
///
class HomeViewModel with ChangeNotifier {
  int pageCount = 0;
  List<HomeBannerEntity?>? bannerList;
  List<HomeArticleListDatas>? homeList = [];

  //首页banner图片
  Future getBannerData() async {
    List<HomeBannerEntity?>? list = await Api.instance.getBannerData();
    bannerList = list ?? [];
    notifyListeners();
  }

  //首页文章
  Future<List<HomeArticleListDatas>?> _getHomeListData(bool loadMore) async {
    List<HomeArticleListDatas>? list =
        await Api.instance.getHomeListData("$pageCount");
    if (list != null && list.isNotEmpty) {
      return list;
    } else {
      //已经加载再最后一页或者加载的数据为空，
      if (loadMore && pageCount > 0) {
        pageCount--;
      }
      return [];
    }
  }

  //首页置顶文章
  Future<List<HomeArticleListDatas>?> _getHomeTopListData(bool loadMore) async {
    if (loadMore) {
      return [];
    }
    List<HomeArticleListDatas>? list = await Api.instance.getHomeTopListData();
    return list;
  }

  //初始化首页文章列表
  Future initHomeListData(bool loadMore, {ValueChanged<bool>? callback}) async {
    //加载更多
    if (loadMore) {
      pageCount++;
    } else {
      pageCount = 0;
      homeList?.clear();
    }
    //先获取置顶数据
    _getHomeTopListData(loadMore).then((topList) {
      //第一次加载数据
      if (!loadMore) {
        homeList?.addAll(topList ?? []);
      }
      //再获取首页列表
      _getHomeListData(loadMore).then((allList) {
        homeList?.addAll(allList ?? []);
        notifyListeners();

        callback?.call(loadMore);
      });
    });
  }

  //收藏站内文章
  Future<bool?> collect(String articleId,int index) async{
    bool? success = await Api.instance.collect(articleId);
    if(success == true){
      homeList?[index].collect = true;
      notifyListeners();
    }
    return success;
  }

  //取消收藏
  Future<bool?> unCollect(String articleId,int index) async{
    bool? success = await Api.instance.unCollect(articleId);
    if(success == true){
      homeList?[index].collect = false;
      notifyListeners();
    }
    return success;
  }
}
